﻿//自定义layui模块，用于本项目后台通用操作
layui.define(['table', 'layer', 'notice','nicescroll'], function (exports) {
    var $ = layui.jquery,
        layer = layui.layer,
        table = layui.table,
        notice = layui.notice,
        cmswh = {
            //批量操作
            batOperate: function (url, key, batmsg) {
                if (!batmsg) {
                    batmsg = "确认操作吗？";
                }
                var checkStatus = table.checkStatus('ltable');
                if (checkStatus.data.length > 0) {
                    var data = checkStatus.data;
                    layer.confirm(batmsg, { icon: 3, title: '提示' }, function (index) {
                        var operate = notice.msg('操作执行中...', { icon: 4, close: true });
                        //请求
                        $.ajax({
                            url: url,
                            type: 'POST',
                            traditional: true,
                            data: { ids: data.map(function (e) { return e[key]; }) },
                            success: function (res) {
                                notice.destroy();
                                if (res.status == 1) {
                                    notice.success({
                                        message: res.msg,
                                        timeout: 2000,
                                        position: 'topCenter',
                                        onClosed: function () {
                                            //重新加载数据
                                            var loading = layer.msg('数据请求中', { icon: 16, shade: 0.01, time: 0 });
                                            table.reload('ltable', { done: function (res, curr, count) { layer.close(loading); } });
                                        }
                                    });
                                }
                                else {
                                    notice.error({ message: res.msg, timeout: 2000, position: 'topCenter' });
                                }
                            },
                            error: function (err) {
                                notice.destroy();
                                notice.error({ message: err, timeout: 2000, position: 'topCenter' });
                            }
                        });
                        layer.close(index);
                    });
                }
                else {
                    layer.msg("请选中您要操作的记录！", { icon: 2, time: 1000 });
                    return;
                }
            },
            //单个操作
            operate: function (url, data) {
                layer.confirm('确认操作吗？', { icon: 3, title: '提示' }, function (index) {
                    var operate = notice.msg('操作执行中...', { icon: 4, close: true });
                    //请求
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        success: function (res) {
                            notice.destroy();
                            if (res.status == 1) {
                                //成功的提示
                                notice.success({
                                    message: res.msg,
                                    timeout: 2000,
                                    position: 'topCenter',
                                    onClosed: function () {
                                        //重新加载数据
                                        var loading = layer.msg('数据请求中', { icon: 16, shade: 0.01, time: 0 });
                                        table.reload('ltable', { done: function (res, curr, count) { layer.close(loading); } });
                                    }
                                });
                            }
                            else {
                                notice.error({ message: res.msg, timeout: 2000, position: 'topCenter' });
                            }
                        },
                        error: function (err) {
                            notice.destroy();
                            notice.error({ message: err, timeout: 2000, position: 'topCenter' });
                        }
                    });
                    layer.close(index);
                });
            },
            //通用发送请求
            request: function (url, type, data, callBack) {
                //loading层
                var loading2 = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });
                //请求
                $.ajax({
                    url: url,
                    type: type,
                    data: data,
                    success: function (res) {
                        layer.close(loading2);
                        if (res.status == 1) {
                            notice.msg(res.msg, { icon: 1, timeout: 2000 });
                            if (typeof (callBack) === "function") {
                                callBack(res);
                            }
                        }
                        else {
                            notice.error({ message: res.msg, timeout: 2000, position: 'topCenter' });
                        }
                    },
                    error: function (err) {
                        layer.close(loading2);
                        notice.error({ message: err, timeout: 2000, position: 'topCenter' });
                    }
                });
            },
            // 保存信息
            save: function (url, data, callback) {
                //loading层
                var loading2 = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });

                //请求
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    success: function (res) {
                        layer.close(loading2);
                        if (res.status == 1) {
                            //成功的提示
                            notice.success({
                                message: res.msg,
                                timeout: 2000,
                                position: 'topCenter',
                                onClosed: function () {
                                    var llayer = window.parent.layer;
                                    //关闭窗口
                                    var index = parent.layer.getFrameIndex(window.name);
                                    llayer.close(index);
                                    //刷新父窗口表格
                                    if (window.parent.layui.table) {
                                        var loading = llayer.msg('数据请求中', { icon: 16, shade: 0.01, time: 0 });
                                        window.parent.layui.table.reload('ltable', {
                                            done: function (res, curr, count) {
                                                llayer.close(loading);
                                            }
                                        });
                                    }
                                    //预留回调
                                    if (typeof (callback) === "function") {
                                        callback();
                                    }
                                }
                            });
                        }
                        else {
                            notice.error({ message: res.msg, timeout: 2000, position: 'topCenter' });
                        }
                    },
                    error: function (err) {
                        layer.close(loading2);
                        notice.error({ message: err, timeout: 2000, position: 'topCenter' });
                    }
                });
            },
            // 关闭窗体
            close: function () {
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            },
            //关闭当前窗口，重载列表
            reload: function () {
                var llayer = window.parent.layer;
                //关闭窗口
                var index = parent.layer.getFrameIndex(window.name);
                llayer.close(index);
                //刷新父窗口表格
                if (window.parent.layui.table) {
                    var loading = llayer.msg('数据请求中', { icon: 16, shade: 0.01, time: 0 });
                    window.parent.layui.table.reload('ltable', {
                        done: function (res, curr, count) {
                            llayer.close(loading);
                        }
                    });
                }
            },
            //绑定数据
            dataBind: function (url, where, is_page, reset) {
                var argNum = arguments.length;
                if (argNum == 1 || argNum == 2) {
                    is_page = true;
                }
                //loading
                var loading = layer.msg('数据请求中', { icon: 16, shade: 0.01, time: 0 });
                var response = {
                    statusCode: 1 //重新规定成功的状态码为 200，table 组件默认为 0
                }, parseData = function (res) { //将原始数据解析成 table 组件所规定的数据
                    return {
                        "code": res.status, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.totalCount, //解析数据长度
                        "data": res.item //解析数据列表
                    };
                };
                var options, page;
                if (is_page) {
                    page = { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                        layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                        , groups: 10 //只显示 1 个连续页码
                        , first: false //不显示首页
                        , last: false //不显示尾页
                    };
                } else {
                    page = false;
                }
                //重置第一页
                options = {
                    url: url
                    , cellMinWidth: 100
                    , skin: 'line'
                    , size: 'lg'
                    , even: true
                    , toolbar: true
                    , where: where
                    //数据渲染完成的回调
                    , done: function (res, curr, count) {
                        layer.close(loading);
                    }
                    , page: page
                    , response: response
                    , parseData: parseData
                };
                table.reload('ltable', options);
            },
            //获取自定义id集合
            batIds: function (url, batmsg) {
                if (!batmsg) {
                    batmsg = "确认操作吗？";
                }
                var $row = $("#ltable .checkall");
                var ids = [];
                $($row).each(function (i, item) {
                    var checkbox = $(item).find("input:checkbox");
                    if (checkbox.prop("checked")) {
                        var id = checkbox.val();
                        ids.push(parseInt(id));
                    }
                });
                if (ids.length > 0) {
                    layer.confirm(batmsg, { icon: 3, title: '提示' }, function (index) {
                        //请求
                        $.ajax({
                            url: url,
                            type: 'POST',
                            traditional: true,
                            data: { ids: ids },
                            success: function (res) {
                                if (res.status == 1) {
                                    notice.success({
                                        message: res.msg,
                                        timeout: 2000,
                                        position: 'topCenter',
                                        onClosed: function () {
                                            location.reload();
                                        }
                                    });
                                }
                                else {
                                    notice.error({ message: res.msg, timeout: 2000, position: 'topCenter' });
                                }
                            },
                            error: function (err) {
                                notice.error({ message: err, timeout: 2000, position: 'topCenter' });
                            }
                        });
                        layer.close(index);
                    });
                } else {
                    notice.error({ message: '请选中您要操作的记录！', timeout: 2000, position: 'topCenter' });
                    return;
                }
            },
            //全选
            batChecked: function () {
                form.on('checkbox(checkall)', function (data) {
                    var isChecked = data.elem.checked;
                    if (isChecked) {
                        $(".checkboxitem").prop("checked", true)
                    } else {
                        $(".checkboxitem").prop("checked", false)
                    }
                    form.render('checkbox')
                })
            },
            /*增加方法*/
            //弹出一个询问窗口
            jsdialog: function (msgtitle, msgcontent, url, callback) {
                var argnum = arguments.length; //参数个数
                notice.error({
                    title: msgtitle,
                    message: msgcontent,
                    timeout: 5000,
                    position: 'topCenter',
                    onClosed: function () {
                        if (url == "back") {
                            //history.back(-1);
                        } else if (url != "") {
                            location.href = url;
                        }
                        //执行回调函数
                        if (argnum == 4) {
                            callback();
                        }
                    }
                });
            },
            //设置快捷菜单的高度
            setPopMenuHeight: function () {
                //计算容器的高度
                var divHeight = $(window).height() * 0.6;
                var groupHeight = 0;
                $("#pop-menu .list-box .list-group").each(function () {
                    if ($(this).height() > groupHeight) {
                        groupHeight = $(this).height();
                    }
                });
                if (divHeight > groupHeight) {
                    divHeight = groupHeight;
                }
                $("#pop-menu .list-box .list-group").height(groupHeight);
                $("#pop-menu .pop-box").height(divHeight);
            },
            //快捷菜单的显示与隐藏
            togglePopMenu: function () {
                if ($("#pop-menu").css("display") == "none") {
                    $("#pop-menu").show();
                    //只有显示的时候才能设置高度
                    cmswh.setPopMenuHeight();
                    //设置导航滚动条
                    $("#pop-menu .list-box").niceScroll({ touchbehavior: false, cursorcolor: "#ccc", cursoropacitymax: 0.6, cursorwidth: 5, autohidemode: false });
                } else {
                    $("#pop-menu").hide();
                    $("#pop-menu .list-box").getNiceScroll().remove();
                }
            },
            //设置快捷菜单容器的大小
            popMenuTreeResize: function () {
                //计算容器的宽度
                var groupWidth = $("#pop-menu .list-box .list-group").outerWidth();
                var divWidth = $("#pop-menu .list-box .list-group").length * groupWidth;
                var winWidth = $(window).width();
                if (divWidth > winWidth) {
                    var groupCount = Math.floor(winWidth / groupWidth);
                    if (groupCount > 0) {
                        groupWidth = groupWidth * groupCount;
                    }
                } else {
                    groupWidth = divWidth;
                }
                $("#pop-menu .pop-box").width(groupWidth);
                //只有显示的时候才能设置高度
                if ($("#pop-menu").css("display") == "block") {
                    cmswh.setPopMenuHeight();
                    //重设导航滚动条
                    $("#pop-menu .list-box").getNiceScroll().resize();
                }
            },
            //初始化快捷导航菜单
            initPopMenuTree: function () {
                //遍历及加载事件
                $("#pop-menu .pop-box .list-box li").each(function () {
                    var linkObj = $(this).children("a");
                    linkObj.removeAttr("href");
                    if ($(this).children("ul").length > 0) { //如果无下级菜单
                        linkObj.addClass("nolink");
                    } else {
                        linkObj.addClass("link");
                        linkObj.click(function () {
                            //linkMenuTree(true, linkObj.attr("navid")); //加载函数
                        });
                    }
                });

                //设置快捷菜单容器的大小
                cmswh.popMenuTreeResize();
            },
            //初始化导航菜单
            initMenuTree: function () {
                var navObj = $("#main-nav");
                var navGroupObj = $("#sidebar-nav .list-group");

                navGroupObj.each(function (i) {
                    var navParent = $(this);
                    //添加菜单导航
                    var navHtml = $('<li class="layui-nav-item layui-hide-xs sidebar-main" lay-unselect><a nav-bind="xt' + (i + 1) + '">' + $.trim(navParent.children("a").text()) + '</a></li>').appendTo(navObj);
                    //默认选中第一项
                    if (i == 0) {
                        navParent.show();
                        navHtml.addClass("layui-this");
                    }
                    var navItemObj = navParent.find("dl.layui-nav-child:eq(0)");
                    navParent.parent().html(navItemObj.html());
                });

                if (navGroupObj.length > 0) {
                    var navSm = $("#main-nav-more");
                    navGroupObj.each(function (i) {
                        var navParent = $(this);
                        $(navSm).append('<dd lay-unselect><a nav-bind="xt' + (i + 1) + '">' + $.trim(navParent.children("a").text()) + '</a></dd>');
                    });
                }
            },
            //插入值到表单类型
            InValue: function (id, Value) {
                $('#' + id).val(Value);
            },
            //全选取消按钮函数
            checkAll: function (chkobj) {
                if ($(chkobj).text() == " 全选") {
                    $(chkobj).children("span").text(" 取消");
                    $(".checkall input:enabled").prop("checked", true);
                } else {
                    $(chkobj).children("span").text(" 全选");
                    $(".checkall input:enabled").prop("checked", false);
                }
            },
            //检查短信字数
            checktxt: function (obj, txtId) {
                var txtCount = $(obj).val().length;
                if (txtCount < 1) {
                    return false;
                }
                var smsLength = Math.ceil(txtCount / 62);
                $("#" + txtId).html("您已输入<b>" + txtCount + "</b>个字符，将以<b>" + smsLength + "</b>条短信扣取费用。");
            },
            //定时转向提示
            zsRedirect: function (msgtitle, url, ms) {
                layer.msg(msgtitle, { time: ms }, function () {
                    if (url != "") {
                        window.location.href = url;
                    }
                });
            },
            //可以自动关闭的提示
            jsprint: function (msgtitle, url, callback) {
                var argNum = arguments.length;
                notice.success({
                    message: msgtitle,
                    timeout: 2000,
                    position: 'topCenter',
                    onClosed: function () {
                        if (url == "back" || url == "") {

                        } else {
                            //url = url.replace("../", "/admin/");
                            admin.refresh(url);
                        }

                        //执行回调函数
                        if (argNum == 3) {
                            callback();
                        }
                    }
                });
            },
            //获取防伪标记
            headerRequestVerificationToken: function () {
                var token = $("input[name='__RequestVerificationToken']").val();
                var headers = {};
                //防伪标记放入headers

                //也可以将防伪标记放入data
                headers["__RequestVerificationToken"] = token;
                return headers;
            },
            //初始化Tree目录结构
            initCategoryHtml: function (parentObj, layNum) {
                $(parentObj).find('li.layer-' + layNum).each(function (i) {
                    var liObj = $(this);
                    var nextNum = layNum + 1;
                    if (liObj.next('.layer-' + nextNum).length > 0) {
                        cmswh.initCategoryHtml(parentObj, nextNum);
                        var newObj = $('<ul></ul>').appendTo(liObj);
                        cmswh.moveCategoryHtml(liObj, newObj, nextNum);
                    }
                });
            },
            moveCategoryHtml: function (liObj, newObj, nextNum) {
                if (liObj.next('.layer-' + nextNum).length > 0) {
                    liObj.next('.layer-' + nextNum).appendTo(newObj);
                    cmswh.moveCategoryHtml(liObj, newObj, nextNum);
                }
            },
            //form更新渲染
            render: function () {
                form.render();
            }
        };

    //接口输出
    exports('cmswh', cmswh);
})